<?php

// 编辑器图片上传
// POST common.editUpload

namespace app\api\resource\common;

class EditUpload
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description  = '编辑器图片上传';
    // 参数
    public $_param  = [
        'name'   => '上传控件名称',
        'dir'    => '存储目录,相对应public目录的文件名,默认upload',
        'editor' => '编辑器上传,可选',
    ];
    // 返回
    public $_return = [
        201 => '上传成功',
        422 => '参数不正确',
        400 => '上传异常',
    ];

    public function run(&$request)
    {
        $params['name'] = $request->param('name/s','editormd-image-file','trim');
        $params['dir']  = $request->param('dir/s','upload','trim');
        $params['file'] = $request->file($params['name']);

        $rule = [
            'name' => 'require',
            'dir'  => 'require',
            'file' => 'require|image|fileExt:png,jpg,gif,jpeg|fileSize:838860',
        ];
        $msg = [
            'name.require'  => '名称必须',
            'dir.require'   => '目录必须',
            'file.require'  => '文件必须[1]',
            'file.image'    => '文件必须为图片',
            'file.fileExt'  => '文件后缀必须为[png|jpg|gif|jpeg]',
            'file.fileSize' => '文件大小必须小于[838860]',
        ];
        $validate = new \think\Validate($rule,$msg);
        if (!$validate->check($params)) {
            $errMsg = $validate->getError();
            header('HTTP/1.1 200 Ok');
            header('Content-Type:application/json;charset=utf-8');
            echo 'error|' . $errMsg;
            exit;
        }

        $uri  = ROOT_PATH . 'public' . DS . $params['dir'];
        if ( !file_exists($uri) ) {
            mkdir($uri,0755);
        }

        $file = $params['file'];
        $info = $file->move($uri);
        if ($info) {
        	header('HTTP/1.1 200 Ok');
        	header('Content-Type:application/json;charset=utf-8');
            $uri = '/public/' . $params['dir'] . '/' . date('Ymd') . '/' . $info->getFilename();
            $arr = [
            	'success' => 1,
            	'message' => 'success',
            	'url'     => $uri
            ];
            echo json_encode($arr, JSON_UNESCAPED_UNICODE);
            exit;
        } else {
            header('HTTP/1.1 200 Ok');
            header('Content-Type:application/json;charset=utf-8');
            $arr = [
            	'success' => 0,
            	'message' => 'error'
            ];
            echo json_encode($arr, JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
}